package practise.alogrithm.hundredInterviewQuestions;

import java.util.Stack;

/**
 * Created by richard on 6/2/14.
 */
public class ConvertWordsInSentence {

    public static void main(String[] args){
        System.out.println("result:"+convertWords("I am a students."));
    }
    public static String convertWords(String sentence){
        String newString = swap(sentence);// there we don't need to swap, just need to get the letter from last to first
        int index = 0;
        StringBuilder stringBuilder = new StringBuilder();
        while (newString.indexOf(" ",index)!=-1){
            stringBuilder.append(swap(newString.substring(index, newString.indexOf(" ", index)))).append(" ");
            index = newString.indexOf(" ",index)+1;
        }
        stringBuilder.append(newString.substring(index));
        return stringBuilder.toString();
    }

    private static String swap(String string){
        if(string.length()==0){
            return "";
        }
        Stack<Character> stack = new Stack<>();
        for(char ch : string.toCharArray()){
            stack.push(ch);
        }
        StringBuilder stringBuilder = new StringBuilder();
        while (!stack.isEmpty()){
            stringBuilder.append(stack.pop());
        }
        return stringBuilder.toString();
    }
}
